package cn.main.web;

import cn.main.core.SessionKey;
import com.mysql.jdbc.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Author: chengwei
 * Date:   2016/7/14
 * Time:   13:56
 */
public class UserFilter implements Filter {
    
    private String loginUrl;

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String loginUrl = filterConfig.getInitParameter("loginUrl");
        if (loginUrl != null && !"".equals(loginUrl)) {
            this.loginUrl = loginUrl;
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpSession session = request.getSession();
            if (session != null && session.getAttribute(SessionKey.SESSION_KEY) != null) {
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        servletRequest.getRequestDispatcher(loginUrl).forward(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
